/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.gr.uth.homework5infodisplayer;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author mruiz
 */
public class LogAPI {

    public static void clearLog(String logFilePath) {
       try {
            // Create file 
            FileWriter fstream = new FileWriter(logFilePath);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("");
            //Close the output stream
            out.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }

    public static void writeInLog(String text, String logFilePath) {
        try {
            // Create file 
            FileWriter fstream = new FileWriter(logFilePath, true);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("\n" + text);
            //Close the output stream
            out.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }

    public static void checkLogSizeAndClean(String logFilePath) throws IOException {
        File file = new File(logFilePath);

        long filesize = file.length();
        long filesizeInKB = filesize / 1024;
        if (filesizeInKB > 1.0) {
            Scanner scanner = new Scanner(file);
            ArrayList<String> coll = new ArrayList<String>();
            scanner.nextLine();
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                coll.add(line);
            }

            scanner.close();

            FileWriter writer = new FileWriter(file);
            for (String line : coll) {
                writer.write("\n" + line);
            }

            writer.close();
        }
    }
}
